package ee.android.kinokavad.activities;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;

import ee.android.kinokavad.App;
import ee.android.kinokavad.R;
import ee.android.kinokavad.data.Movie;
import ee.android.kinokavad.utils.LogUtils;
import ee.android.kinokavad.utils.LogUtils.Logger;
import ee.android.kinokavad.utils.NetworkUtils;

public class MovieSummaryActivity extends SherlockActivity implements OnClickListener{

	private static final String TAG = MovieSummaryActivity.class.getSimpleName();
	private Movie mMovie;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.movie_summary_activity);
		
		getSupportActionBar().setSubtitle(getIntent().getStringExtra("actionBarSubtitle"));
		
		long id = getIntent().getLongExtra("movieId", 0);
		App kinokavad = (App) getApplicationContext();
		kinokavad.getDataController().open();
		mMovie = kinokavad.getDataController().loadMovieByNetId(id);
		kinokavad.getDataController().closeRequest();
		
		initFields();

	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return ((BitmapDrawable) ((ImageView)findViewById(R.id.movieSummaryImage)).getDrawable()).getBitmap();
	}
	
	private void initFields() {

		if (mMovie != null) {
			
			Bitmap picture = (Bitmap) getLastNonConfigurationInstance();
			
			if (picture == null) {
				if (NetworkUtils.isNetworkAvailable(this)) {
					if (mMovie.getPoster() != null && !mMovie.getPoster().equals("")) {
						DownloadFile downloadFile = new DownloadFile();
						downloadFile.execute(mMovie.getPoster());	
					} else if (mMovie.getPictureLink() != null && !mMovie.getPictureLink().equals("")) {
						DownloadFile downloadFile = new DownloadFile();
						downloadFile.execute(mMovie.getPictureLink());	
					} 
				} else {
					setSupportProgressBarVisibility(false);
				}
			} else {
				ImageView pictureView = (ImageView) findViewById(R.id.movieSummaryImage);
				pictureView.setImageBitmap(picture);
				setSupportProgressBarVisibility(false);
			}

			TextView titleView = (TextView) findViewById(R.id.movieSummaryTitle);
			titleView.setText(mMovie.getTitle());
			TextView descriptionView = (TextView) findViewById(R.id.movieSummaryDescription);
			descriptionView.setText(mMovie.getDescription());
			TextView genreView = (TextView) findViewById(R.id.movieSummaryGenre);
			if (mMovie.getGenre() != null) {
				genreView.setText(mMovie.getGenre().replace(",", ", "));
			}
			findViewById(R.id.movieSummaryImdb).setOnClickListener(this);
			findViewById(R.id.movieSummaryYoutube).setOnClickListener(this);
			TextView duration = (TextView) findViewById(R.id.movieSummaryDuration);
			TextView ratingText = (TextView) findViewById(R.id.movieSummaryRatingText);
			RatingBar rating = (RatingBar) findViewById(R.id.movieSummaryRating);
			rating.setEnabled(false);
			if (mMovie.getDuration() != null
					&& !mMovie.getDuration().toLowerCase(Locale.ENGLISH).equals("n/a")) {
				duration.setText("Kestvus: " + mMovie.getDuration());
			} else {
				duration.setVisibility(View.GONE);
			}
			if (mMovie.getImdbRating() != null
					&& !mMovie.getImdbRating().toLowerCase(Locale.ENGLISH).equals("n/a")) {
				ratingText.setText(mMovie.getImdbRating());
				try {
					rating.setRating(Float.parseFloat(mMovie.getImdbRating()));
				} catch (NumberFormatException e) {
					rating.setVisibility(View.GONE);
				}
			} else {
				rating.setVisibility(View.GONE);
				ratingText.setVisibility(View.GONE);
			}
		} else {
			Toast.makeText(this, "Kahjuks filmi kohta täiendav info puudub.", Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
	}


	// usually, subclasses of AsyncTask are declared inside the activity class.
	// that way, you can easily modify the UI thread from here
	private class DownloadFile extends AsyncTask<String, Integer, Bitmap> {
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected Bitmap doInBackground(String... sUrl) {
			try {
				URL url = new URL(sUrl[0]);
				URLConnection connection = url.openConnection();
				connection.connect();
				// this will be useful so that you can show a typical 0-100% progress bar
				int fileLength = connection.getContentLength();

				// download the file
				InputStream input = new BufferedInputStream(url.openStream());
				//				OutputStream output = new FileOutputStream("/sdcard/file_name.extension");
				ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
				byte data[] = new byte[1024];
				long total = 0;
				int count;
				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					publishProgress((int) (total * 100 / fileLength));
					byteBuffer.write(data, 0, count);
				}

				Bitmap bm = BitmapFactory.decodeByteArray(byteBuffer.toByteArray(), 0, byteBuffer.toByteArray().length);
				byteBuffer.flush();
				byteBuffer.close();
				input.close();
				return bm;
			} catch (Exception e) {
				Logger.e(TAG, e);
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);
			int result = (Window.PROGRESS_END - Window.PROGRESS_START) / 100 * progress[0];
			Logger.d(TAG, "Progress:" + result);
			setSupportProgress(result);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (result != null) {
				ImageView pictureView = (ImageView) findViewById(R.id.movieSummaryImage);
				pictureView.setImageBitmap(Bitmap.createScaledBitmap(result, (int) (result.getWidth()*1.2), (int) (result.getHeight()*1.2), true));
				result.recycle();
			}
			setSupportProgressBarVisibility(false);
		}

	}

	@Override
	public void onClick(View v) {

		String url = null;

		switch (v.getId()) {
		case R.id.movieSummaryImdb:
			url = mMovie.getImdbLink();
			break;

		case R.id.movieSummaryYoutube:
			url = mMovie.getYoutubeLink();
			break;

		default:
			break;
		}

		if (url != null && !url.equals("")) {
			try {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				startActivity(browserIntent);
			} catch (ActivityNotFoundException e) {
				Logger.e(TAG, e);
			}

		} else {
			Toast.makeText(this, "Kahjuks see link puudub", Toast.LENGTH_SHORT).show();
		}


	}
 
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
//			NavUtils.navigateUpFromSameTask(this);
			return true;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		LogUtils.onStartSession(this);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		LogUtils.onEndSession(this);
	}


}
